export const createCdHelper = (second) => {
  let endTime;
  let timer;
  const startCD = (onUpdate, onEnd) => {
    if (timer) {
      return;
    }
    const storageCDENDTime = localStorage.getItem("CDENDTIME");
    if (storageCDENDTime) {
      endTime = parseInt(storageCDENDTime);
    } else {
      endTime = Date.now() + second * 1000;
    }
    const getRemainSecond = (endTime) => {
      const remainTime = Math.round((endTime - Date.now()) / 1000);
      return remainTime;
    };
    let remainTime = getRemainSecond(endTime);
    if (remainTime <= 0) {
      return;
    }
    localStorage.setItem("CDENDTIME", endTime);
    onUpdate(remainTime);
    timer = setInterval(() => {
      if (Date.now() >= endTime) {
        localStorage.removeItem("CDENDTIME");
        clearInterval(timer);
        timer = null;
        onEnd();
      } else {
        remainTime = getRemainSecond(endTime);
        onUpdate(remainTime);
      }
    }, 1000);
  };
  const checkIsCD = () => {
    const storageCDENDTime = localStorage.getItem("CDENDTIME");
    return !!storageCDENDTime;
  };
  return {
    checkIsCD,
    startCD,
  };
};

export const filterEffectObj = (targetObj, checkEffect) => {
  const resultObj = {};
  const keys = Object.keys(targetObj);
  keys.forEach((key) => {
    if (checkEffect(targetObj[key])) {
      resultObj[key] = targetObj[key];
    }
  });
  return resultObj;
};

export const dateTransform = (date, type ="YYYY-MM-DD") => {
  if(typeof date === "string") {
    return date;
  }

  const padZeroWhenLessThanTwo = (num) => {
    const numStr = num.toString();
    return numStr.padStart(2, "0");
  };
  const year = date.getFullYear();
  const month = padZeroWhenLessThanTwo(date.getMonth() + 1);
  const day = padZeroWhenLessThanTwo(date.getDate());
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  if (type === "YYYY-MM-DD") {
    return `${year}-${month}-${day}`;
  } else {
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  }
};
// 获取当前Date和对应的年月日，以及7天前的Date和对应的年月日
export function getDateAnd7DaysAgo() {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, "0");
  const day = String(today.getDate()).padStart(2, "0");
  const sevenDaysAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
  const sevenYear = sevenDaysAgo.getFullYear();
  const sevenMonth = String(sevenDaysAgo.getMonth() + 1).padStart(2, "0");
  const sevenDay = String(sevenDaysAgo.getDate()).padStart(2, "0");
  return {
    today: {
      date: today,
      dateStr: `${year}-${month}-${day}`,
    },
    sevenDaysAgo:{
      date: sevenDaysAgo,
      dateStr: `${sevenYear}-${sevenMonth}-${sevenDay}`,
    },
  };
}
// iso格式日期转换为date
export const isoToDate = (isoDate) => {
  const date = new Date(isoDate);
  return date;
};